<?php


namespace App\Http\Rest\Member\Resource;

use App\Exceptions\BusinessException;
use App\Foundation\SmsCodeHelper;
use App\Foundation\PasswordHelper;
use App\Foundation\PhoneHelper;
use App\Foundation\Utils\CNYMoney;
use App\Http\Rest\Member\DBRest;
use Framework\Foundation\Config;
use Framework\Foundation\Database\FDB;
use Framework\Foundation\Event\EventDispatcher;
use Framework\Foundation\Response\ResponseGen;
use Framework\Foundation\Request\ServerRequest;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Cookie\SetCookie;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key;

class Member extends DBRest
{
    public function getList(array $restParams, $request)
    {
        return $this->getInfo($restParams, $request);
    }

    public function getInfo(array $restParams, $request)
    {
        $restParams['id'] = $request->getAttribute('member_id');
        if (empty($restParams['id'])) {
            throw new BusinessException("未登录");
        }
        $query = FDB::from($restParams['resource'])
            ->select(['member_id', 'username', 'mobile', 'email', 'account_balance', 'vip_level', 'shared_by'], true)
            ->where($restParams['field'], $restParams['id']);
        $info = $query->fetch();

        if (isset($info['account_balance'])) {
            $info['account_balance_human'] = CNYMoney::intToHuman($info['account_balance']);
        }
        return ResponseGen::success($info);
    }

    /**
     * @param array $restParams
     * @param $request ServerRequest
     * @throws \Exception
     */
    public function add(array $restParams, $request)
    {
        // 验证输入的参数
        $phone = $request->getIn('phone');
        $password = $request->getIn('password');
        $code = $request->getIn('code');
        $platform = $request->getIn('platform');

        $cookies = $request->getCookieParams();
        if (empty($platform)) {
            $platform = $cookies['platform'] ?? '';
        }

        $remember = $request->getIn('keep_sign_in');
        $jumpUrl = $request->getIn('jump_url', '/member/userinfo_detail.html');

        if ($password != $request->getIn('re_password')) {
            throw new \Exception("两次密码不一致");
        }

        $phoneHelper = new PhoneHelper();
        if (!$phoneHelper->checkRule($phone)) {
            throw new \Exception("手机号码不正确");
        }

        // 验证码
//        $codeHelper = new SmsCodeHelper();
//
//        if ($code != 6666) {
//            if (!$codeHelper->verifyCode($phone, $code)) {
//                throw new \Exception("验证码验证不正确");
//            }
//        }


        $passwordHelper = new PasswordHelper();

        $data = [
            'mobile' => $phone,
            'password' => $passwordHelper->encryptWord($password),
            'platform' => $platform,
        ];

        if (isset($cookies['shared_by'])) {
            $data['shared_by'] = $cookies['shared_by'];
        }

        // 添加用户
        $memberModel = new \App\Http\Rest\Member\Model\Member();
        $ret = $memberModel->add($data);
        if (!$ret) {
            return ResponseGen::error(600, "注册失败");
        }
        // 发布注册事件
        /**
         * @var $eventDispatch EventDispatcher;
         */
//        $eventDispatch = Container::instance()->get('eventDispatch');
//        $eventDispatch->dispatch(new MemberRegister());

        $key = Config::instance()->get('member.jwt.key');
        $token = (new Builder())
            ->withClaim("uid", $ret)
            ->expiresAt(time() + 86400 * 30)
            ->getToken(new Sha256(), new Key($key));
        $tokenString = $token->__toString();

        if (!empty($remember)) {
            $cookie = new SetCookie([
                'Name' => 'Authorization',
                'Value' => $token->__toString(),
                'Expires' => time() + 86400 * 30
            ]);
        } else {
            $cookie = new SetCookie(['Name' => 'Authorization', 'Value' => $tokenString]);
        }


        if ($request->isAjax()) {
            $response = ResponseGen::success([
                'token' => $token->__toString(),
                'info' => ['member_id' => $ret],
                'jump_url' => $jumpUrl . '?code=' . $tokenString
            ], "注册成功");
        } else {
            $response = ResponseGen::locationJump($jumpUrl . '?code=' . $tokenString);
        }

        $response = $response->withHeader('Set-Cookie', $cookie->__toString());
        return $response;
    }

    // 注销
    public function delete(array $restParams, $request)
    {
    }
}
